import * as vscode from "vscode";
import * as fs from 'fs';
import apiIndex from './api/index';

export class ViewProvider implements vscode.WebviewViewProvider {
  public static readonly viewType = "hephaestusAIView";
  private _view?: vscode.WebviewView;

  constructor(private readonly _extensionUri: vscode.Uri, private readonly _extensionContext: vscode.ExtensionContext) { }

  public resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext, _token: vscode.CancellationToken) {
    this._view = webviewView;
    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [this._extensionUri],
      enableCommandUris: true
    };
    webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

    // // 消息监听
    // webviewView.webview.onDidReceiveMessage(async message => {
    //   if (message.command === 'sendPrompt') {
    //     try {
    //       const prompt = message.prompt;
    //       const promptHistory = message.promptHistory;
    //       const response = await apiIndex.callDeepSeekAPI(prompt, promptHistory);
    //       console.log('response: ', response);
    //       const jsonResponse = JSON.parse(response);
    //       const text = jsonResponse.choices[0]['message']['content'];
    //       webviewView.webview.postMessage({
    //         command: 'showResponse',
    //         response: {
    //           id: message.id,
    //           content: { text },
    //           response: jsonResponse,
    //         }
    //       });
    //     } catch (err: any) {
    //       console.log('onDidReceiveMessage: ', err);
    //       webviewView.webview.postMessage({
    //         command: 'error',
    //         error: err.message
    //       });
    //     }
    //   }
    // }, undefined, this._extensionContext.subscriptions);
  }

  private _getHtmlForWebview(webview: vscode.Webview) {
    const htmlPath = vscode.Uri.joinPath(this._extensionUri, 'out', 'ui', 'chat.html');
    const resourcesPath = vscode.Uri.joinPath(this._extensionUri, 'out', 'resources');
    const webviewUri = webview.asWebviewUri(resourcesPath);
    let htmlContent = fs.readFileSync(htmlPath.fsPath, 'utf-8');

    // 替换资源路径
    htmlContent = htmlContent.replace(
      /\${webviewUri}/g,
      webviewUri.toString()
    );
    return htmlContent;
  }
}

export function activate(context: vscode.ExtensionContext) {
  const provider = new ViewProvider(context.extensionUri, context);
  context.subscriptions.push(vscode.window.registerWebviewViewProvider(ViewProvider.viewType, provider));
}

export function deactivate() { }
